package mysql_conn

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"strconv"
	"sync"
)

var DbInstance *gorm.DB
var once sync.Once

func initDB() {
	host := os.Getenv("DB_HOST")
	username := os.Getenv("DB_USERNAME")
	password := os.Getenv("DB_PASSWORD")
	portStr := os.Getenv("DB_PORT")
	port := 3306
	if portStr == "" {
		port, _ = strconv.Atoi(portStr)
	}
	database := os.Getenv("DB_DATABASE")
	charset := os.Getenv("DB_CHARSET")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&loc=Local&parseTime=true", username, password, host, port, database, charset)
	fmt.Println(dsn)
	mysqlDb := mysql.Open(dsn)

	db, err := gorm.Open(mysqlDb, &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	sqlDb, _ := db.DB()
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)

	DbInstance = db
}

func GetDb() *gorm.DB {
	once.Do(initDB)
	return DbInstance
}

func GetSession() *gorm.DB {
	once.Do(initDB)

	if os.Getenv("APP_ENV") != "prod"{
		return DbInstance.Debug()
	}

	return DbInstance.Session(&gorm.Session{})
}
